package com.sise.wangzhan.command;

import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;

import java.util.*;

/**
 * @Classname CollapserCommand
 * @Description TODO    合并请求:   条件：针对相同的请求来合并(请求名相同，但是请求的参数不同)
 *
 * @Date 2020/4/29 20:07
 * @Created by wangzhan
 */
public class CollapserCommand extends HystrixCommand<Map<String , CollapserCommand.Person>> {

    //请求集合，第一个类型是单个请求返回的数据类型，第二个是请求参数的类型
    Collection<HystrixCollapser.CollapsedRequest<Person, String>> requests;

    protected CollapserCommand(Collection<HystrixCollapser.CollapsedRequest<Person, String>> requests) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")));

        this.requests = requests;
    }

    @Override
    protected Map<String, Person> run() throws Exception {
        System.out.println("收集参数后执行命令，参数数量："+ requests.size());
        //处理参数
        List<String> personNames = new ArrayList<>();
        for (HystrixCollapser.CollapsedRequest<Person, String> request : requests){
            personNames.add(request.getArgument());
        }
        //调用服务，根据名称获取Person的Map
        Map<String, Person> result = callService(personNames);

        return result;
    }

    //模拟服务返回
    private Map<String, Person> callService(List<String> personNames){
        Map<String, Person> result = new HashMap<String, Person>();
        for (String personName : personNames){
            Person p = new Person();
            p.id = UUID.randomUUID().toString();
            p.name = personName;
            p.age = new Random().nextInt(30);
            result.put(personName, p);
        }
        return result;
    }



    public static class Person{
        String id;
        String name;
        Integer age;

        @Override
        public String toString() {
            return "Person{" +
                    "id='" + id + '\'' +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}


